#define _CRT_SECURE_NO_WARNINGS
#include"binarytree.h"

BTNode* BinaryTreeCreate(BTDateType* a, int n, int* pi)
{
	assert(a);
	assert(pi);
	if (a[*pi] == '#')
	{
		(*pi)++;
		return NULL;
	}
	BTNode* root = (BTNode*)malloc(sizeof(BTNode));
	if (root == NULL)
	{
		perror("malloc");
		return NULL;
	}
	root->date = a[*pi];
	(*pi)++;
	root->left = BinaryTreeCreate(a, n, pi);
	root->right = BinaryTreeCreate(a, n, pi);
	return root;
}

void BinaryTreeDestroy(BTNode* root)
{
	if (root == NULL)
	{
		return;
	}
	BinaryTreeDestroy(root->left);
	BinaryTreeDestroy(root->right);
	free(root);
}

int BinaryTreeSize(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	else
	{
		return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
	}
}

int BinaryTreeLeafSize(BTNode* root)
{
	if (root == NULL)
	{
		return 0;
	}
	if (root->left == NULL && root->right == NULL)
	{
		return 1;
	}
	else
	{
		return BinaryTreeLeafSize(root->left) + BinaryTreeLeafSize(root->right);
	}
}

int BinaryTreeLevelKSize(BTNode* root , int k)
{
	if (root == NULL || k <= 0)
	{
		return 0;
	}
	if (k == 1 && root != NULL)
	{
		return 1;
	}
	else
	{
		return BinaryTreeLevelKSize(root->left, k - 1) + BinaryTreeLevelKSize(root->right, k - 1);
	}
}

BTNode* BinaryTreeFind(BTNode* root, BTDateType x)
{
	if (root == NULL)
	{
		return NULL;
	}
	if (root->date == x)
	{
		return root;
	}
	BTNode* find = BinaryTreeFind(root->left, x);
	if (find)
	{
		return find;
	}
	find = BinaryTreeFind(root->right, x);
	if (find)
	{
		return find;
	}
	return NULL;
}

void BinaryTreePrevOrder(BTNode* root)
{
	if (root == NULL)
	{
		return;
	}
	printf("%c ", root->date);
	BinaryTreePrevOrder(root->left);
	BinaryTreePrevOrder(root->right);
}

void BinaryTreeInOrder(BTNode* root)
{
	if (root == NULL)
	{
		return;
	}
	BinaryTreePrevOrder(root->left);
	printf("%c ", root->date);
	BinaryTreePrevOrder(root->right);
}

void BinaryTreePostOrder(BTNode* root)
{
	if (root == NULL)
	{
		return;
	}
	BinaryTreePrevOrder(root->left);
	BinaryTreePrevOrder(root->right);
	printf("%c ", root->date);
}

void BinaryTreeLevelOrder(BTNode* root)
{
	Queue list;
	QueueInit(&list);
	QueuePush(&list, root);
	while (QueueEmpty(&list) != 1)
	{
		BTNode* front = QueueFront(&list);
		printf("%c ", QueueFront(&list)->date);
		QueuePop(&list);
		if(front->left!=NULL)QueuePush(&list, front->left);
		if(front->right!=NULL)QueuePush(&list, front->right);
	}
}

int BinaryTreeComplete(BTNode* root)
{
	Queue list;
	QueueInit(&list);
	QueuePush(&list, root);
	while (QueueFront(&list) != NULL)
	{
		BTNode* front = QueueFront(&list);
		QueuePop(&list);
		QueuePush(&list, front->left);
		QueuePush(&list, front->right);
	}
	while (QueueFront(&list) == NULL)
	{
		QueuePop(&list);
		if (QueueEmpty(&list) == 1)return 1;
	}
	return 0;
}